package middleware

import (
	"net/http"
	"rego-top/dto"
	"rego-top/models"
	"rego-top/services"
	"rego-top/utils"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, dto.ErrorResponse("未提供认证令牌", nil))
			c.Abort()
			return
		}

		token := utils.ExtractTokenFromHeader(authHeader)
		if token == "" {
			c.JSON(http.StatusUnauthorized, dto.ErrorResponse("无效的认证令牌格式", nil))
			c.Abort()
			return
		}

		claims, err := utils.ValidateToken(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, dto.ErrorResponse("无效的认证令牌", err.Error()))
			c.Abort()
			return
		}

		// 获取用户信息
		userService := services.NewUserService()
		user, err := userService.GetUserByID(claims.UserID)
		if err != nil {
			c.JSON(http.StatusUnauthorized, dto.ErrorResponse("用户不存在", nil))
			c.Abort()
			return
		}

		if !user.IsActive {
			c.JSON(http.StatusUnauthorized, dto.ErrorResponse("账户已被禁用", nil))
			c.Abort()
			return
		}

		// 将用户信息存储到上下文中
		c.Set("user", user)
		c.Set("user_id", user.ID)
		c.Set("username", user.Username)
		c.Set("email", user.Email)

		c.Next()
	}
}

// OptionalAuthMiddleware 可选认证中间件（不强制要求认证）
func OptionalAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader != "" {
			token := utils.ExtractTokenFromHeader(authHeader)
			if token != "" {
				claims, err := utils.ValidateToken(token)
				if err == nil {
					userService := services.NewUserService()
					user, err := userService.GetUserByID(claims.UserID)
					if err == nil && user.IsActive {
						c.Set("user", user)
						c.Set("user_id", user.ID)
						c.Set("username", user.Username)
						c.Set("email", user.Email)
					}
				}
			}
		}
		c.Next()
	}
}

// GetCurrentUser 从上下文中获取当前用户
func GetCurrentUser(c *gin.Context) (*models.User, bool) {
	if user, exists := c.Get("user"); exists {
		if u, ok := user.(*models.User); ok {
			return u, true
		}
	}
	return nil, false
}

// GetCurrentUserID 从上下文中获取当前用户ID
func GetCurrentUserID(c *gin.Context) (uint, bool) {
	if userID, exists := c.Get("user_id"); exists {
		if id, ok := userID.(uint); ok {
			return id, true
		}
	}
	return 0, false
}

// RequireEmailVerification 要求邮箱验证的中间件
func RequireEmailVerification() gin.HandlerFunc {
	return func(c *gin.Context) {
		user, exists := GetCurrentUser(c)
		if !exists {
			c.JSON(http.StatusUnauthorized, dto.ErrorResponse("未认证", nil))
			c.Abort()
			return
		}

		if !user.IsEmailVerified {
			c.JSON(http.StatusForbidden, dto.ErrorResponse("请先验证邮箱", nil))
			c.Abort()
			return
		}

		c.Next()
	}
}